package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class searchReceiver {
    @Autowired
    private SearchService searchService;
    /**
     * 监听RabbitMQ队列，处理特定的专辑上线消息
     * 本方法通过RabbitListener注解指定监听的队列、交换机和路由键
     * 当接收到消息时，根据消息中的专辑ID执行上线操作，并确认处理完成
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM,durable = "true"),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void upperAlbum(Long albumId, Message message, Channel channel) {
        // 检查专辑ID是否非空，若非空则调用服务方法执行专辑上线操作
        if (null!=albumId){
            searchService.upperAlbum(albumId);
        }
        // 尝试确认消息处理完成，如果失败则抛出异常
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 处理专辑下架的消息
     * 当接收到专辑下架的消息时，此方法会被触发
     * 它从指定的队列中接收消息，并执行专辑下架的逻辑
     *
     * @param albumId 专辑ID，用于标识需要下架的专辑
     * @param message RabbitMQ消息对象，包含消息的详细信息
     * @param channel RabbitMQ通道对象，用于消息的确认
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM,durable = "true"),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void lowerAlbum(Long albumId, Message message, Channel channel) {
        // 检查专辑ID是否非空，若非空则调用服务方法执行专辑下架操作
        if (null!=albumId){
            searchService.lowerAlbum(albumId);
        }
        try {
            // 消息处理完成后，确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            // 如果消息确认过程中发生IO异常，则抛出运行时异常
            throw new RuntimeException(e);
        }
    }
}
